package com.wryyyyy.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.Objects;
import java.util.UUID;

@Slf4j
@Component
public class FileLoad {
    public String uploadOneFile(String path, MultipartFile file) {
        // 1.获取文件名
        String fileName = file.getOriginalFilename();
        assert fileName != null;
        int index = fileName.lastIndexOf(".");
        int pointIndex = fileName.length()-(fileName.length()-index);
        String name = fileName.substring(0, pointIndex);
        String etc = fileName.substring(pointIndex);
        log.debug("后缀："+etc);
        // file.getSize();//B
        // 5MB : 5 * 1024 * 1024 B
        if (!Objects.equals(etc, ".xlsx")) {
            return null;
        }
        // 2.给文件重命名，避免重复覆盖的情况
        String uuid = UUID.randomUUID().toString().replace("-","");
        uuid = uuid.substring(0, 10);
        fileName = name + "_" + uuid + etc;
        log.debug("fileName："+fileName);
        // 3.获取要存储的路径
        String targetPath = "";
        targetPath = this.getProjectPath();
        targetPath = targetPath + "//src//main//resources//static//"+path+"//" + fileName;
        // 4.写入文件
        try {
            file.transferTo(new File(targetPath));
            return fileName;
        } catch (IOException e){
            e.printStackTrace();
        }
        return null;
    }

    private String getProjectPath() {
        ApplicationHome applicationHome = new ApplicationHome(this.getClass());
        return applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath();
    }
}